<template>
  <div class="full" v-loading="loading" element-loading-text="用例拼命运行中，请稍等..."
       element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.6)">
    <div>
      <!--面包屑-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>接口测试</el-breadcrumb-item>
        <el-breadcrumb-item>套件管理</el-breadcrumb-item>
      </el-breadcrumb>
      <!--卡片-->
      <el-card class="box-card">
        <el-row :gutter="20">
          <!--搜索框-->
          <el-col :span="6">
            <el-input placeholder="请输入套件名称" v-model="queryParams.name" clearable @clear="getTestSuiteList" @keyup.enter.native="getTestSuiteList">
              <el-button slot="append" icon="el-icon-search" @click="getTestSuiteList" class="search"></el-button>
            </el-input>
          </el-col>
          <!--创建按钮-->
          <el-col :span="4">
            <el-button type="primary" @click="openAddTestSuiteDialog" plain>创建套件</el-button>
          </el-col>
        </el-row>
        <!--表格-->
        <el-table :data="testSuiteList" :cell-style="cellStyle" border stripe>
          <el-table-column label="#" type="index"></el-table-column>
          <el-table-column label="套件名称" prop="name"></el-table-column>
          <el-table-column label="所属项目" prop="project"></el-table-column>
          <el-table-column label="创建时间" prop="create_time"></el-table-column>
          <el-table-column label="操作" min-width="77px">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="openRunTestSuiteDialog(scope.row)" plain>运 行</el-button>
              <el-button type="warning" size="mini" @click="openEditTestSuiteDialog(scope.row)" plain>编 辑</el-button>
              <el-button type="danger" size="mini" @click="deleteThisTestSuite(scope.row.id)" plain>删 除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分页-->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.p"
          :page-sizes="[5, 10, 20, 40]"
          :page-size="queryParams.s"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </el-card>
      <!--新建套件对话框-->
      <el-dialog title="创建套件" :visible.sync="addTestSuiteDialogVisible" width="40%" :append-to-body="true"
                 :close-on-click-modal="false" :close-on-press-escape="false" @close="addDialogClose">
        <!--套件表单-->
        <el-form :model="addTestSuiteForm" status-icon :rules="addTestSuiteRule" ref="addTestSuiteRef" label-width="90px">
          <el-form-item label="所属项目" prop="project_id">
            <el-select v-model="addTestSuiteForm.project_id" placeholder="请选择所属项目"  @change="addProjectChange">
              <el-option
                v-for="project in projectAndInterfaceNames"
                :key="project.id"
                :label="project.name"
                :value="project.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="套件名称" prop="name">
            <el-input v-model="addTestSuiteForm.name" placeholder="请输入套件名称"></el-input>
          </el-form-item>
          <el-form-item label="选择用例" prop="cases">
            <el-cascader v-model="choiceTestCases"
                         :options="interfaceAndTestCases"
                         :props="{value: 'id', label: 'name', children: 'testcase', multiple: true}"
                         placeholder="请勾选用例"
                         style="width: 80%"
                         collapse-tags
                         clearable></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addTestSuiteDialogClose">取 消</el-button>
          <el-button type="primary" @click="addTestSuite">确 定</el-button>
        </span>
      </el-dialog>
      <!--编辑套件对话框-->
      <el-dialog title="编辑套件" :visible.sync="editTestSuiteDialogVisible" width="40%" :append-to-body="true"
                 :close-on-click-modal="false" :close-on-press-escape="false" @close="editDialogClose">
        <!--套件表单-->
        <el-form :model="editTestSuiteForm" status-icon :rules="editTestSuiteRule" ref="editTestSuiteRef" label-width="90px">
          <el-form-item label="所属项目" prop="project_id">
            <el-select v-model="editTestSuiteForm.project_id" placeholder="请选择所属项目"  @change="editProjectChange">
              <el-option
                v-for="project in projectAndInterfaceNames"
                :key="project.id"
                :label="project.name"
                :value="project.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="套件名称" prop="name">
            <el-input v-model="editTestSuiteForm.name" placeholder="请输入套件名称"></el-input>
          </el-form-item>
          <el-form-item label="选择用例" prop="cases">
            <el-cascader v-model="choiceTestCases"
                         :options="interfaceAndTestCases"
                         :props="{value: 'id', label: 'name', children: 'testcase', multiple: true}"
                         placeholder="请勾选用例"
                         style="width: 80%"
                         collapse-tags
                         clearable></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editTestSuiteDialogClose">取 消</el-button>
          <el-button type="primary" @click="editThisTestSuite">确 定</el-button>
        </span>
      </el-dialog>
      <!--运行套件对话框-->
      <el-dialog title="运行套件" :visible.sync="runTestSuiteDialogVisible" width="20%" :append-to-body="true"
                 :close-on-click-modal="false" :close-on-press-escape="false" @close="runDialogClose">
        <el-form :model="runTestSuiteForm" status-icon :rules="runTestSuiteRule" ref="runTestSuiteRef" label-width="90px">
          <el-form-item label="运行环境" prop="env_id">
            <el-select v-model="runTestSuiteForm.env_id" placeholder="请选择运行环境">
              <el-option
                v-for="env in environmentList"
                :key="env.id"
                :label="env.name"
                :value="env.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="runTestSuiteDialogClose">取 消</el-button>
        <el-button type="primary" @click="runThisTestSuite">开 始</el-button>
      </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getProjectAndInterfaceNames,
  getEnvironmentNames,
  createTestSuite,
  getTestSuites,
  editTestSuite,
  deleteTestSuite,
  runTestSuite
} from '../../api/api'

export default {
  created () {
    this.getTestSuiteList()
    this.getProjectAndInterfaceNameList()
  },
  data () {
    return {
      queryParams: {
        p: 1,
        s: 10,
        name: ''
      },
      tmpName: '',
      addTestSuiteForm: {
        project_id: '',
        name: '',
        cases: []
      },
      choiceTestCases: [],
      editTestSuiteForm: {},
      testSuiteList: [],
      suiteId: '',
      projectAndInterfaceNames: [],
      total: 0,
      addTestSuiteDialogVisible: false,
      editTestSuiteDialogVisible: false,
      interfaceAndTestCases: [],
      tmpInterfaceId: '',
      tmpChoiceTestCase: [],
      addTestSuiteRule: {
        project_id: [
          { required: true, message: '所属项目不能为空！', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '套件名称不能为空！', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符！', trigger: 'blur' }
        ]
      },
      editTestSuiteRule: {
        project_id: [
          { required: true, message: '所属项目不能为空！', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '套件名称不能为空！', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符！', trigger: 'blur' }
        ]
      },
      // 运行
      loading: false,
      environmentList: [],
      runSuiteId: '',
      runTestSuiteDialogVisible: false,
      runTestSuiteForm: {
        env_id: ''
      },
      runTestSuiteRule: {
        env_id: [
          { required: true, message: '运行环境不能为空！', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 获取测试套件列表
    getTestSuiteList () {
      if (this.queryParams.name !== this.tmpName) {
        this.tmpName = this.queryParams.name
        this.queryParams.p = 1
      }
      getTestSuites(this.queryParams)
        .then(response => {
          if (response.data.code !== 0) return this.$message.error('获取套件列表失败！')
          this.testSuiteList = response.data.data.results
          this.total = response.data.data.count
        })
    },
    // 获取项目名称列表
    getProjectAndInterfaceNameList () {
      getProjectAndInterfaceNames()
        .then(response => {
          if (response.data.code !== 0) return this.$message.error('获取项目名称列表失败！')
          this.projectAndInterfaceNames = response.data.data
        })
    },
    // 打开创建套件对话框
    openAddTestSuiteDialog () {
      this.choiceTestCases = []
      this.interfaceAndTestCases = []
      this.addTestSuiteDialogVisible = true
    },
    // 获取环境名称列表
    getEnvironmentNameList () {
      getEnvironmentNames()
        .then(response => {
          if (response.data.code !== 0) return this.$message.error('获取环境名称列表失败！')
          this.environmentList = response.data.data
        })
    },
    // 打开运行套件对话框
    openRunTestSuiteDialog (suiteInfo) {
      this.runSuiteId = suiteInfo.id
      this.getEnvironmentNameList()
      this.runTestSuiteDialogVisible = true
    },
    // 运行套件
    runThisTestSuite () {
      this.$refs.runTestSuiteRef.validate(valid => {
        if (!valid) return
        this.loading = true
        this.runTestSuiteDialogVisible = false
        runTestSuite(this.runSuiteId, this.runTestSuiteForm)
          .then(response => {
            if (response.data.code !== 0) {
              this.loading = false
              return this.$message.error(response.data.message.run)
            }
            this.loading = false
            this.$message.success(response.data.message.run)
            this.runSuiteId = ''
            this.runTestSuiteForm = { env_id: '' }
          })
      })
      this.getTestSuiteList()
    },
    // 运行对话框关闭
    runDialogClose () {
      this.$refs.runTestSuiteRef.resetFields()
      this.environmentList = []
    },
    // 运行套件对话框关闭
    runTestSuiteDialogClose () {
      this.runTestSuiteDialogVisible = false
      this.runDialogClose()
      this.runSuiteId = ''
      this.runTestSuiteForm = {
        env_id: ''
      }
    },
    // 打开编辑套件对话框
    openEditTestSuiteDialog (suiteInfo) {
      this.choiceTestCases = []
      this.interfaceAndTestCases = []
      this.editTestSuiteForm = { ...suiteInfo }
      this.suiteId = this.editTestSuiteForm.id
      delete this.editTestSuiteForm.id
      delete this.editTestSuiteForm.project
      delete this.editTestSuiteForm.create_time
      this.editProjectChange()
      this.tmpChoiceTestCase = JSON.parse(this.editTestSuiteForm.cases)
      for (const interface1 of this.interfaceAndTestCases) {
        this.tmpInterfaceId = interface1.id
        for (const testcase1 of interface1.testcase) {
          for (const kid of this.tmpChoiceTestCase) {
            if (testcase1.id === kid) {
              this.choiceTestCases.push([this.tmpInterfaceId, kid])
            }
          }
        }
      }
      this.editTestSuiteDialogVisible = true
    },
    // 创建套件
    addTestSuite () {
      this.addTestSuiteForm.cases = []
      if (this.choiceTestCases.length !== 0) {
        for (const case1 of this.choiceTestCases) {
          this.addTestSuiteForm.cases.push(case1[1])
        }
      }
      this.addTestSuiteForm.cases = '[' + String(this.addTestSuiteForm.cases) + ']'
      this.$refs.addTestSuiteRef.validate(valid => {
        if (!valid) return
        createTestSuite(this.addTestSuiteForm)
          .then(response => {
            if (response.data.code !== 0) return this.$message.error('创建套件失败！')
            this.$message.success('创建套件成功！')
            this.addTestSuiteDialogClose()
            this.getTestSuiteList()
          })
      })
    },
    // 编辑套件
    editThisTestSuite () {
      this.editTestSuiteForm.cases = []
      if (this.choiceTestCases.length !== 0) {
        for (const case1 of this.choiceTestCases) {
          this.editTestSuiteForm.cases.push(case1[1])
        }
      }
      this.editTestSuiteForm.cases = '[' + String(this.editTestSuiteForm.cases) + ']'
      this.$refs.editTestSuiteRef.validate(valid => {
        if (!valid) return
        editTestSuite(this.suiteId, this.editTestSuiteForm)
          .then(response => {
            if (response.data.code !== 0) return this.$message.error('编辑套件失败！')
            this.$message.success('编辑套件成功！')
            this.editTestSuiteDialogClose()
            this.getTestSuiteList()
          })
      })
    },
    // 创建对话框关闭
    addDialogClose () {
      this.$refs.addTestSuiteRef.resetFields()
      this.addTestSuiteForm = {
        project_id: '',
        name: '',
        cases: []
      }
    },
    // 编辑对话框关闭
    editDialogClose () {
      this.$refs.editTestSuiteRef.resetFields()
      this.editTestSuiteForm = {}
    },
    // 创建套件对话框关闭
    addTestSuiteDialogClose () {
      this.addTestSuiteDialogVisible = false
      this.addDialogClose()
    },
    // 编辑套件对话框关闭
    editTestSuiteDialogClose () {
      this.editTestSuiteDialogVisible = false
      this.editDialogClose()
    },
    // 删除套件
    deleteThisTestSuite (suiteId) {
      this.$confirm('此操作将永久删除该套件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteTestSuite(suiteId).then(response => {
          if (response.data.code !== 0) return this.$message.error('删除套件失败！')
          this.$message.success('删除套件成功！')
          this.total -= 1
          if (this.total === (this.queryParams.p - 1) * this.queryParams.s && this.total !== 0) {
            this.queryParams.p -= 1
          }
          this.getTestSuiteList()
        })
      }).catch(err => err)
    },
    // 创建对话框项目改变
    addProjectChange () {
      this.choiceTestCases = []
      for (const project of this.projectAndInterfaceNames) {
        if (project.id === this.addTestSuiteForm.project_id) {
          this.interfaceAndTestCases = project.interface
        }
      }
    },
    // 编辑对话框项目改变
    editProjectChange () {
      for (const project of this.projectAndInterfaceNames) {
        if (project.id === this.editTestSuiteForm.project_id) {
          this.interfaceAndTestCases = project.interface
        }
      }
    },
    // 监听size变化
    handleSizeChange (newSize) {
      this.queryParams.s = newSize
      this.getTestSuiteList()
    },
    // 监听页码变化
    handleCurrentChange (newPage) {
      this.queryParams.p = newPage
      this.getTestSuiteList()
    },
    // 表格样式
    cellStyle (data) {
      if (data.column.label === '套件名称') {
        return 'color: #409EFF'
      }
    }
  }
}
</script>

<style lang="less" scoped>
  /deep/ .el-dialog__body {
    padding: 20px 35px 10px 20px;
  }
</style>
